<template>
  <div>
    <editor v-model="myValue" :init="init" />
  </div>
</template>

<script setup>
import tinymce from "tinymce/tinymce"
import Editor from "@tinymce/tinymce-vue"
import "tinymce/themes/silver"
import "tinymce/icons/default/icons"
import "tinymce/plugins/image" // 插入上传图片插件
import "tinymce/plugins/media" // 插入视频插件
import "tinymce/plugins/table" // 插入表格插件
import "tinymce/plugins/lists" // 列表插件
import "tinymce/plugins/wordcount" // 字数统计插件
import "tinymce/plugins/code" // 源码
import "tinymce/plugins/link" // 超链接
import "tinymce/plugins/preview" // 预览
import "tinymce/plugins/fullscreen" //全屏
import "tinymce/plugins/charmap" //特殊字符
import "/public/tinymce/bdmap" //地图插件
import "tinymce/icons/default/icons.min.js"
import "/public/tinymce/langs/zh_CN.js" //中文包
import { reactive, ref } from "vue"
import { onMounted, defineEmits, watch, onUnmounted } from "@vue/runtime-core"
import http from "@/utils/js/http.js"
import { ElMessage } from "element-plus"
const emits = defineEmits(["getContent"])
const props = defineProps({
    value: {
        type: String,
        default: () => {
            return ""
        },
    },
    disabled: {
        type: Boolean,
        default: false,
    },
    plugins: {
        type: [String, Array],
        default:
            "lists image media table wordcount fullscreen code link preview charmap bdmap",
    },
    toolbar: {
        type: [String, Array],
        default:
            " bold italic forecolor backcolor charmap| formatselect |undo redo |  alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | lists image media table  | code removeformat link preview fullscreen bdmap |",
    },
    uploadUrl: {
        type: String,
        default: "/web/image",
    },
    height: {
        type: Number,
        default: 500,
    },
})
const myValue = ref(props.value)
const init = reactive({
    content_css: "tinymce/skins/content/default/content.css",
    language: "zh_CN", //语言
    skin_url: "tinymce/skins/ui/oxide", // skin路径
    height: props.height, //编辑器高度
    branding: false, //是否禁用“Powered by TinyMCE”
    menubar: false, //顶部菜单栏显示
    image_dimensions: false, //去除宽高属性
    plugins: props.plugins,
    toolbar: props.toolbar,
    paste_convert_word_fake_lists: false, // 插入word文档需要该属性
    paste_webkit_styles: "all",
    paste_merge_formats: true,
    nonbreaking_force_tab: false,
    paste_auto_cleanup_on_paste: false,
    media_poster: false,
    media_alt_source: false,

    //图片上传
    images_upload_handler: async (blobInfo, success, failure) => {
        let formdata = new FormData()
        formdata.append("file", blobInfo.blob())
        // console.log(blobInfo.blob())
        const RES = await http.upload(props.uploadUrl, formdata)
        if (RES.code == 200) {
            success(RES.data)
        } else {
            failure("网络波动导致上传出错，请重新上传！")
        }

        // tinyMCE.execCommand("mceReplaceContent", false, "<img src=>")     //听说很有用
    },
    file_picker_types: "image media",
    //文件上传
    file_picker_callback: function (callback, value, meta) {
        var filetype = ".mp4"
        //模拟出一个input用于添加本地文件
        var input = document.createElement("input")
        input.setAttribute("type", "file")
        input.setAttribute("accept", filetype)
        input.click()

        input.onchange = function (e) {
            var file = this.files[0]
            let extArr = file.name.split(".")
            let ext = extArr[extArr.length - 1]
            if (ext !== "mp4") {
                ElMessage({
                    message: "上传资源只能是 mp4 格式的视频!",
                    duration: 5000,
                    customClass: "zZindex",
                })
                return false
            }

            var formdata = new FormData()
            formdata.append("file", file)
            http.upload(props.uploadUrl, formdata).then((RES) => {
                callback(RES.data, { title: file.name })
            })
            //返回地址
        }
    },
    media_url_resolver: function (data, resolve) {
        try {
            var videoUri = encodeURI(data.url)
            if (data.url.indexOf(".mp4") > -1) {
                // 判断是否mp4  否则用ifarme嵌套
                var embedHtml =
                    '<p style="text-align: left">' +
                    '<video src="' +
                    data.url +
                    '" width="100%" height="auto" style="max-width: 100%;" allowfullscreen="false" controls="controls" controlslist="nodownload"></video>' +
                    "</p>"
                resolve({ html: embedHtml })
            } else {
                var embedHtml =
                    "<p>" +
                    '<iframe frameborder="0" src="' +
                    data.url +
                    '" width="100%" height="100%" style="max-width: 100%;"></iframe>' +
                    "</p>"
                resolve({ html: embedHtml })
            }
        } catch (e) {
            resolve({ html: "" })
        }
    },
})
watch(
    () => props.value,
    () => {
        myValue.value = props.value
        emits("getContent", myValue.value)
    }
)
watch(
    () => myValue.value,
    () => {
        emits("getContent", myValue.value)
    }
)
onMounted(() => {
    tinymce.init({})
})
onUnmounted(() => {
    tinymce.remove()
})
</script>

<style lang="scss" scoped></style>
